import { getPerformProcess, getPerformData, getPerformLog, getDismiss, confrimDismiss, getSubmitPm, getUserBtnAuthority } from "../../api/manage"
import { getUserInfoByUserDDId } from "../../api/index"
import create from 'dd-store'
import pageStore from '../../stores/globalStore'


create.Page({
  store: pageStore,
  data: {
    userDDId: '',
    progress: [],
    // dimension: [],
    pmlog: [],
    avatar: '',
    dept: '',
    userName: '',
    selectList: [
    ],
    visile: false,
    modaltxt: '',
    basicTwoVisible: false,
    nowPmProgressId: '',
    pmProgressId: '',
    makeid: '',
    value: '',
    // 当前绩效详情页面的员工ID
    pmId: '',
    performancedetailToIntendedTargetPageParameter: {
    },
    taskList: [],
    mannerList: [],
    dimensionOkList: [],
    // 按钮显示的数组
    showBtnList: [],
    // 当前流程信息
    currentProgressInfo: {},

    // 驳回流程列表
    rebutList: [],
    // 该绩效所属用户id
    pmInUserId: '',
    // 该绩效所属用户上级用户id
    pmInManagerUserId: ''
  },
  onLoad(options) {
    console.log('绩效页面接收数据', options);
    let data = {
      pmId: options.pmid
    }
    this.setData({
      avatar: options.avatar,
      dept: options.dept,
      userName: options.userName,
      pmId: options.pmid,
      pmInUserId: options.userId,
      pmInManagerUserId: options.managerUserId
    })
    dd.getStorage({
      key: 'currentCity',
      success: (res) => {
        // this.data.userDDId = res.data.value
        this.setData({
          makeid: res.data.value.userId
        })
      },
      fail: function (res) {
        dd.alert({ content: res.errorMessage });
      }
    });
    // 流程
    this.getstep()
    // 获取按钮权限数据
    this.getUserBtnAuthorityFunc()
  },

  // 评分点击事件
  scoreClick() {
    // 判断是自评还是上级评分
    dd.getStorage({
      key: 'currentCity',
      success: (res) => {
        console.log('登录人信息', res.data.value);
        let loginInfo = res.data.value
        let progressInfo = this.data.progress.filter((item) => {
          return item.pmProgressCompleteStatus == 1
        })[0]
        console.log('当前流程信息', progressInfo);
        let scoreType = ''
        if (progressInfo.pmProgressName.indexOf("上级评分") != -1) {
          scoreType = 'sjpf'
        } else if (progressInfo.pmProgressName.indexOf("自评") != -1) {
          scoreType = 'zp'
        }
        dd.navigateTo({
          url: `/pages/usual/performancedetail/modules/scorePage/scorePage?userId=${loginInfo
            .userId}&managerUserDDId=${loginInfo.managerUserDDId}&makeUserDDId=${progressInfo.makeUserDDId}&pmId=${this.data.pmId}&avatar=${this.data.avatar}&pmProgressId=${progressInfo.pmProgressId}&scoreType=${scoreType}`
        })
      },
      fail: function (res) {

      }
    });
  },
  // 流程方法
  async getstep() {
    let data = {
      pmId: this.data.pmId
    }
    await getPerformProcess(data).then(rs => {
      console.log(rs);
      rs.data.sort((a, b) => a.sort - b.sort)
      // let list = rs.data
      // let resdd = list
      let currentProgressInfo
      rs.data.forEach((item) => {
        if (item.pmProgressCompleteStatus == 1) {
          currentProgressInfo = item
        }
        if (item.pmStageCode == '0019') {
          currentProgressInfo = item
        }
      })
      console.log('当前流程信息', currentProgressInfo);
      this.setData({
        progress: rs.data,
        nowPmProgressId: currentProgressInfo.pmProgressId
      })

      // 调用按钮权限创建函数
      this.createBtnAuthFunc()
    })
    await getPerformData(data).then(rs => {
      rs.data.sort((a, b) => a.sort - b.sort)
      this.setData({
        dimension: rs.data
      })
    })
    await getPerformLog(data).then(rs => {
      this.setData({
        pmlog: rs.data
      })
    })


  },
  handlepopup() {
    // this.visilestatus(true)
    console.log(1);
    let tData = {
      nowPmProgressId: ""
    }

    let prgs = this.data.progress
    prgs.forEach((prg) => {
      if (prg.pmProgressCompleteStatus == 1) {
        tData.nowPmProgressId = prg.pmProgressId
      }
    })
    dd.navigateTo({
      url: `/pages/usual/performancedetail/modules/rebut/rebut?nowPmProgressId=${tData.nowPmProgressId}`
    })
    // this.setData({
    //   pickerVisible: true
    // })

  },
  handleTriggerPicker(e) {
    console.log(e);
  },

  handlePopupClose() {
    this.visilestatus()
  },
  handleTriggerControlledPicker(visible, e) {
    console.log('handleTriggerControlledPicker', visible, e);
    this.setData({
      pickerVisible: visible,
    });
  },
  // 按钮权限创建函数
  async createBtnAuthFunc() {
    let btnAuths = []
    let currentUserDDId = dd.getStorageSync({ key: 'currentCity' }).data.value.userId;
    console.log('当前用户的userDDId', currentUserDDId);
    let progressData = this.data.progress
    console.log('流程数据', this.data.progress);
    progressData.forEach((item) => {
      // 找到当前流程
      if (item.pmProgressCompleteStatus == 1) {
        // 查询绩效归属者的用户信息 
        // await getUserInfoByUserDDId()
        console.log('该绩效当前流程:', item.pmProgressName);
        let scopeType = ''
        if (item.pmProgressName.indexOf('上级评分') != -1) {
          scopeType = 'sjpf'
        } else if (item.pmProgressName.indexOf('自评') != -1) {
          scopeType = 'zp'
        }
        console.log('类型');
        this.setData({
          currentProgressInfo: item
        })
        let nPmInUserId = this.data.pmInUserId
        let nPmInManagerUserId = this.data.pmInManagerUserId
        // 不同的流程创建不同的按钮
        switch (item.pmStageCode) {
          case '0016':  // 目标制定
            // 添加功能按钮
            if (item.makeUserDDId == nPmInUserId) {
              btnAuths.push('制定目标')
            }
            break;
          case '0017':  // 目标确认
            console.log('0017');
            // 添加功能按钮
            if (item.makeUserDDId == nPmInManagerUserId && currentUserDDId == item.makeUserDDId) {
              btnAuths.push('目标确认')
              btnAuths.push('调整目标')
              // 添加驳回按钮
              btnAuths.push('驳回')
            }

            break;
          case '0036':  // 执行中

            break;
          case '0018':  // 自评/上级评分
            if (scopeType == 'sjpf') {
              if (currentUserDDId == item.makeUserDDId) {
                btnAuths.push('评分')
                btnAuths.push('驳回')
              }
            } else {
              if (currentUserDDId == item.makeUserDDId) {
                // 添加驳回按钮
                btnAuths.push('评分')
              }
            }

            break;
          case '0019':  // 结束

            break;

          default:
            break;
        }



      }
    })

    console.log('按钮权限数据', btnAuths);
    this.setData({
      showBtnList: btnAuths
    })
  },
  // 请求按钮的权限数据的函数
  async getUserBtnAuthorityFunc() {
    // 从本地缓存读取用户信息
    let storageData = dd.getStorageSync({ key: 'currentCity' });
    let data = {
      pmId: this.data.pmId,
      makeUserDDId: storageData.data.value.userId
    }
    console.log('查询按钮权限参数', data);
    // await getUserBtnAuthority(data).then((res) => {
    //   console.log('查询权限成功', res);
    //   this.setData({
    //     showBtnList: res.data
    //   })
    // })
  },
  /* 步骤一---------------------------------------------------------------------------------------------------------------------------------------- */

  // 将制定目标页面传递过来的数据进行处理的函数
  disposeReturnDataFunc() {
    let newList = this.data.dimensionOkList
    // console.log(newList);
    newList.forEach((item) => {
      item.pmTargetList.forEach((item2, index) => {
        item2.sort = index
      })
    })
    // console.log(newList);
    this.setData({
      dimensionOkList: newList
    })
  },
  // 将制定目标页面制定好的数据保存在当前页面的data数据当中
  saveDataToDataFunc() {
    this.setData({
      dimensionOkList: this.$store.data.dimensionOkList
    })
  },
  // 发送提交请求的函数
  async submitPmApiFunc() {
    // 使用遍历数组的方法，删除不需要的属性
    let newDelData = this.data.dimensionOkList
    newDelData.forEach((item) => {
      delete item.pmDimensionName
      delete item.pmDimensionTypeCode
      delete item.pmDimensionWeight
      delete item.isCustomSelf
      delete item.isImport
      delete item.sort
      item.pmTargetList.forEach((item1) => {
        item1.isBonus = 0
        item1.appointScoreSign = null
      })
    })

    console.log(newDelData);
    // console.log(this.data.dimensionOkList);
    let data = {
      data: newDelData,
      pmProgressId: this.data.progress[0].pmProgressId,
      makeType: 'submit'
    }

    console.log(data);

    await getSubmitPm(data).then(() => {
      console.log('ok');
    })

    // this.onLoad()
    // console.log(data);
  },
  // 回显数据的函数
  returnShowDataFunc() {
    // console.log('需要回显');
    // console.log(this.$store.data);
    // 
    let newArr = this.$store.data.dimensionOkList
    console.log(newArr);
    this.setData({
      dimension: newArr
    })
  },

  // 驳回确认点击事件
  rebutConfirmClick(e) {
    this.visilestatus()
    if (this.data.modaltxt !== '') {
      this.visilestatus(false, true)
    }
    console.log('驳回确认', e);
  },
  // 提交的按钮点击事件
  handleTap(e) {
    this.saveDataToDataFunc()
    this.disposeReturnDataFunc()
    this.submitPmApiFunc()
  },
  cancel() {
    this.visilestatus()
  },
  confirm() {
    this.visilestatus()
    if (this.data.modaltxt !== '') {
      this.visilestatus(false, true)
    }
  },
  visilestatus(state = false, modal = false) {
    this.setData({
      visile: state ? true : false,
      basicTwoVisible: modal ? true : false
    });
  },
  handleClose() {
    this.visilestatus()
  },
  handleSecondaryButtonTap() {
    this.visilestatus()
  },
  handlePrimaryButtonTap() {
    this.visilestatus()
    let data = {
      makeUserDDId: this.data.makeid,
      nowPmProgressId: this.data.nowPmProgressId,
      rebutPmProgressId: this.data.pmProgressId,
      rebutCause: this.data.value
    }
    confrimDismiss(data).then(rs => {
      if (rs.result == "success") {
        this.getstep()
      }
    })
    this.setData({
      value: ''
    })

  },
  onChange(value) {
    this.setData({
      value
    })
  },
  // 制定目标的点击事件
  intendedTargetClick() {
    dd.showToast({
      content: "请在电脑端进行此操作",
      duration: 1500
    })
    // dd.navigateTo({
    //   url: '/pages/usual/performancedetail/modules/intendedTarget/intendedTarget'
    // })
    // // 传参
    // this.$store.data.performancedetailToIntendedTargetPageParameter = {
    //   pmId: this.data.pmId,
    //   nameTitle: this.data.userName,
    //   dept: this.data.dept
    // }
    // this.update()

  },

  // 目标确认点击事件
  async targetAffirmClick() {
    dd.showLoading({
      content: "加载中"
    })
    let newDelData = this.data.dimension
    let subData = []
    newDelData.forEach((item) => {
      delete item.pmDimensionName
      delete item.pmDimensionTypeCode
      delete item.pmDimensionWeight
      delete item.isCustomSelf
      delete item.isImport
      delete item.sort
      subData.push(item)
    })

    let data = {
      pmProgressId: this.data.progress[1].pmProgressId,
      makeType: 'submit',
      data: JSON.stringify(subData)
    }
    console.log('目标确认数据', data, subData);
    await getSubmitPm(data).then((res) => {
      console.log('确认成功', res);
      setTimeout(() => {
        dd.showToast({
          content: "确认成功",
          type: "success",
          duration: 1000
        })
        // 流程
        this.getstep()
        // 获取按钮权限数据
        this.getUserBtnAuthorityFunc()
      }, 100);
    }).finally(() => {
      dd.hideLoading()
    })
  },

  // 调整目标点击事件
  regulatedObjectClick() {
    dd.showToast({
      content: "请在电脑端进行此操作",
      duration: 1500
    })
  },


  /* 步骤一---------------------------------------------------------------------------------------------------------------------------------------- */
  /* 步骤二---------------------------------------------------------------------------------------------------------------------------------------- */
  // 转交按钮的事件函数
  careOfClick() {
    // console.log('转交');
    dd.navigateTo({
      url: '/pages/usual/performancedetail/modules/careOf/careOf/careOf'
    })

    this.$store.data.pmProgressId = this.data.progress[0].pmProgressId
    this.update()
  },
  // 刷新页面的方法
  refreshPageOfOnLoad() {
    this.onShow()
  }
  /* 步骤二---------------------------------------------------------------------------------------------------------------------------------------- */
});

